package com.ay.selfservicemachine.webview;
import com.ay.selfservicemachine.BuildConfig;
import com.ay.selfservicemachine.base.Module;
import com.ay.selfservicemachine.bean.UpdateBean;
import com.ay.selfservicemachine.http.HttpUtils;
import com.ay.selfservicemachine.http.api.LoginApi;
import com.ay.selfservicemachine.utils.JsonUtils;
import com.honghea.rxhttp.exception.ApiException;
import com.honghea.rxhttp.exception.ExceptionEngine;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class WebModule extends Module<IWebViewModuleCallback> {

    void checkAppVersion() {
        Disposable disposable = HttpUtils.getInstance().getRetrofit("http://demo.app.honghea.com/app/api/v1/")
                .create(LoginApi.class)
                .checkAppVersion("hea_work_android", BuildConfig.VERSION_NAME, "ANDROID")
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(t -> getDataCallback().showCheckUpdateDialog())
                .doOnComplete(getDataCallback()::dismissCheckUpdateDialog)
                .map(responseBody -> {
                    String body = responseBody.string();
                    JSONObject json = new JSONObject(body);
                    if (json.optBoolean("STS")) {
                        String data=  json.optString("DATA");
                        try {
                            UpdateBean updateBean = JsonUtils.getInstance().getGson().fromJson(data, UpdateBean.class);
                            return updateBean;
                        }catch (Exception V){
                            return new UpdateBean();
                        }
                    } else {
                        throw new ApiException(json.optString("MSG"), json.optInt("CODE"));
                    }

                })
                .subscribe(
                        updateBean -> {
                            getDataCallback().onCheckUpdateSuccess(updateBean);
                        },
                        t -> {
                            t.printStackTrace();
                            getDataCallback().dismissCheckUpdateDialog();
                            getDataCallback().onCheckUpdateFailed(ExceptionEngine.exceptionHandler(t));
                        }
                );
        disposables.add(disposable);
    }

    List<Disposable> disposables = new ArrayList<>();

    @Override
    public void detachPresenter() {
        for (int i = 0; i < disposables.size(); i++) {
            if (disposables.get(i) != null) {
                disposables.get(i).dispose();
            }
        }
        super.detachPresenter();
    }

}
